<template>
  <div class="app-container">
    <router-link to="advert/create">
      <el-button type="primary" size="small"><i class="el-icon-plus" /> 新增广告</el-button>
    </router-link>

    <el-card class="table_style">
      <el-table :data="adverts" border stripe>
        <el-table-column label="ID" prop="id" width="80" />
        <el-table-column prop="name" label="广告名称" />
        <el-table-column prop="image" label="缩略图">
          <template slot-scope="scope">
            <img :src="scope.row.image" alt="" style="width: 300px;height: 100px">
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="排序">
          <template slot-scope="scope">
            <el-input v-model="scope.row.sort" @change="changeSort(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
import { fetchAdvertList, deleteAdvert, ChangeSortAdvert } from '@/api/advert'

export default {
  data() {
    return {
      adverts: [],
      ruleForm: {
        name: '',
        image: ''
      }
    }
  },
  created() {
    this.init()
  },
  methods: {
    async init() {
      const res = await fetchAdvertList()
      this.adverts = res.data.adverts
    },
    // 点击跳转到编辑页面
    handleEdit(row) {
      this.$router.push({
        name: 'AdvertEdit',
        params: { id: row.id }
      })
    },
    // 修改排序
    async changeSort(row) {
      const res = await ChangeSortAdvert(row.id, row)
      this.init()
      this.$message.success(res.message)
    },
    // 删除
    handleDelete(row) {
      this.$confirm('确认要删除该广告吗, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(async() => {
        const res = await deleteAdvert(row.id)
        this.init()
        this.$message({
          type: 'success',
          message: res.message
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
  }
}
</script>

<style scoped>
.table_style {
  margin-top: 15px;
}
</style>
